package com.bo.sina;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bo.WeiboConfig;
import com.bo.gather.GatherService;
import com.bo.gather.bean.GatherBean;
import com.bo.gather.rule.BaseRule;
import com.bo.gather.rule.RuleService;
import com.bo.sina.send.WeiboResponse;
import com.bo.sina.weibo.access.AccessInfo;
import com.bo.sina.weibo.access.AccessToken;
import com.bo.sina.weibo.login.Login;
import com.bo.startup.CleanLog;
import com.bo.startup.Task;
import com.bo.util.BatchRenamefile;
import com.bo.util.IOUtil;
import com.bo.weibo.WeiboService;
import com.bo.weibo.bean.SendDataInfo;


public class Look extends HttpServlet {
	String root = WeiboConfig.getValue("caijiRule").trim();//"D:\\bo\\caiji\\";//文件夹目录
	/**
	 * Constructor of the object.
	 */
	public Look() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * http://127.0.0.1:8080/weibo/look
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 * @throws WeiboException 
	 * @throws WeiboException 
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException  {
		String action=request.getParameter("action");
		if("weibo".equals(action)){
//			Oauth oauth = new Oauth();  
////			
////			try {
////				BareBonesBrowserLaunch.openURL(oauth.authorize("code","state","scope")); 
////			} catch (WeiboException e1) {
////				// TODO Auto-generated catch block
////				e1.printStackTrace();
////			} 
//////			
////			System.out.print("Hitenter when it's done.[Enter]:");         
////			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         
////			String code = br.readLine();  
//			String code=request.getParameter("code");
//			if(code==null || "".equals(code)){
//				return;
//			}
//			AccessToken accessToken = null;         
//			try {             
//				accessToken = oauth.getAccessTokenByCode(code); 
////				return accessToken.getAccessToken();
//			} catch (WeiboException e) {             
//				e.printStackTrace();         
//			} 
////			
////			
////			String code1=accessToken.getAccessToken();
//			Users um = new Users();
//			um.client.setToken(accessToken.getAccessToken());
//			User user=null;
//			try {
//				
//				user = um.showUserById(accessToken.getUid());
//				Log.logInfo(user.toString());
//			} catch (WeiboException e) {
//				e.printStackTrace();
//			}
//			AccessTokenFile.writeAccessToken(user.getScreenName(),accessToken.getAccessToken());
////			Weibo.accessMap.put(user.getScreenName(),accessToken.getAccessToken());
////			String code=request.getParameter("code");
////			System.out.println(code);
////			if(code1!=null){
////				while(true){
////					Weibo.sendWeibo(Youku.gatherYouku(),code1);
////					System.out.println("睡眠10分钟---------------------------------------------");
////					try {
////						Thread.sleep(1000*60*5);
////					} catch (InterruptedException e) {
////						// TODO Auto-generated catch block
////						e.printStackTrace();
////					}
////				}
////			}
		}else if ("showeditrule".equals(action)){
//			HttpSession session = request.getSession();
			
			
			String key=request.getParameter("key");
			if(key!=null){
//				String str=RuleService.readFile(new File(root+key));
				
				String rulestr=null;
				try {
					rulestr = IOUtil.readFileToString(new File(root+key),  "utf-8");
				} catch (IOException e) {
					e.printStackTrace();
				}
				request.setAttribute("ruledata", rulestr);
				request.setAttribute("key", key);
			}
			
			request.getRequestDispatcher("/editrule.jsp").forward(request,response);
		}else if ("main".equals(action)){
			
//			try {
//				Thread.sleep(1000*30);
//				System.out.println("3333333333");
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}finally{
//				System.out.println("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkk");
//			}
			request.setAttribute("gatherrulemap", BaseRule.gatherRuleMap);
			request.getRequestDispatcher("/main.jsp").forward(request,response);
		}else if ("add".equals(action)){
			request.setAttribute("key", "");
			request.setAttribute("ruledata", "");
			request.getRequestDispatcher("/editrule.jsp").forward(request,response);
		}else if ("setswithc".equals(action)){
			String key=request.getParameter("key");
			GatherBean gatherbean=BaseRule.gatherRuleMap.get(key);
			String isswitch=gatherbean.getWeiboRuleBean().getIsswitch();
			String set=null;
			if("off".equals(isswitch)){
				set="on";
			}else{
				set="off";
			}
			gatherbean.getWeiboRuleBean().setIsswitch(set);
			
			String rulestr=null;
			try {
				rulestr = IOUtil.readFileToString(new File(root+key),  "utf-8");
				int index=rulestr.indexOf("weibo.switch=");
				if(index!=-1){
					String temp=rulestr.substring(0, index+"weibo.switch=".length());
					temp=temp+set;
					//存硬盘
					IOUtil.writeStringToFile(new File(root+key), temp, "utf-8");
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			response.sendRedirect("look?action=main");
		}
		
		
		
		
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String data=request.getParameter("ruledata");
		data=new String(data.getBytes("ISO-8859-1"),"utf-8");
		String key=request.getParameter("key");
		
		
		String action=request.getParameter("postaction");
		if("test1".equals(action)){
			RuleService rule=new RuleService();
			GatherBean gatherbean=rule.calculateRule(data);
			if(gatherbean!=null){
				GatherService gatherService=new GatherService();
				List<Map<String,String>> resultlist=new ArrayList<Map<String,String>>();
				gatherService.calculateParentContent(gatherbean, resultlist);
				StringBuffer sb=new StringBuffer();
				for(Map<String,String> map:resultlist){
					for(Map.Entry<String, String> entry:map.entrySet()){
						sb.append(entry.getKey());
						sb.append("=");
						sb.append(entry.getValue());
						sb.append("\r\n");
					}
					sb.append("\r\n");
				}
				request.setAttribute("showdata", sb.toString());
			}
			
			request.setAttribute("ruledata", data);
			request.setAttribute("key", key);
			
			request.getRequestDispatcher("/editrule.jsp").forward(request,response);
		}else if("test2".equals(action)){
			RuleService rule=new RuleService();
			GatherBean gatherbean=rule.calculateRule(data);
			if(gatherbean!=null){
				GatherService gatherService=new GatherService();
				List<Map<String,String>> resultlist=gatherService.calculateGather(gatherbean);
				if(resultlist!=null){
					StringBuffer sb=new StringBuffer();
					for(Map<String,String> map:resultlist){
						for(Map.Entry<String, String> entry:map.entrySet()){
							sb.append(entry.getKey());
							sb.append("=");
							sb.append(entry.getValue());
							sb.append("\r\n");
						}
						sb.append("\r\n");
					}
					request.setAttribute("showdata", sb.toString());
				}
			}
			request.setAttribute("ruledata", data);
			request.setAttribute("key", key);
			request.getRequestDispatcher("/editrule.jsp").forward(request,response);
		}else if("test3".equals(action)){
			RuleService rule=new RuleService();
			GatherBean gatherbean=rule.calculateRule(data);
			if(gatherbean!=null){
				GatherService gatherService=new GatherService();
				List<Map<String,String>> resultlist=gatherService.calculateGather(gatherbean);
				WeiboService weiboService=new WeiboService();
				List<SendDataInfo> sendDataList=weiboService.calculateSendData(resultlist, gatherbean.getWeiboRuleBean(),gatherbean.getOnlyid());
				StringBuffer sb=new StringBuffer();
				for(SendDataInfo info:sendDataList){
					String s = java.net.URLDecoder.decode(info.getContent(), "utf-8");
					sb.append(s);
					sb.append("\r\n");
//					if(info.getImageItem()!=null){
//						sb.append("有图片");sb.append("\r\n");
//					}
					sb.append("\r\n");
				}
				request.setAttribute("showdata", sb.toString());
			}
			request.setAttribute("ruledata", data);
			request.setAttribute("key", key);
			request.getRequestDispatcher("/editrule.jsp").forward(request,response);
			
		}else if("submit".equals(action)){
			if(key!=null && !"".equals(key.trim())){
				String filename=root+key;
				//存硬盘
				IOUtil.writeStringToFile(new File(filename), data, "utf-8");
				
				
				GatherBean gatherbean=BaseRule.gatherRuleMap.get(key);
				if(gatherbean!=null){
					//存缓存
					RuleService rule=new RuleService();
					GatherBean gatherbean2=rule.calculateRule(data);
					gatherbean.copyBean(gatherbean2);//引用给线程调用
//					gatherbean.getWeiboRuleBean().setIsswitch("off");
				}
			}
			/**
			 * 4.	添加，保存先保存硬盘，后保存内存map<key,value>，并执行线程。测试父节点，测试子节点，测试微博。
			 */
			else{
				//计算文件名
				Date currentTime = new Date();
				SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
				String dateString = formatter.format(currentTime);
				String filename=root+dateString;
				//存硬盘
				IOUtil.writeStringToFile(new File(filename), data, "utf-8");
				
				
				GatherBean gatherbean=BaseRule.gatherRuleMap.get(dateString);
				//不在缓存中
				if(gatherbean==null){
					//存缓存
					RuleService rule=new RuleService();
					GatherBean gatherbean2=rule.calculateRule(data);
					BaseRule.gatherRuleMap.put(dateString, gatherbean2);
					
					//入线程
					Task task=new Task();
					task.setGatherbean(gatherbean2);
					
					Thread thread=new Thread(task);
					thread.start();
				}
			}
			response.sendRedirect("look?action=main");
		}
		
		
}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		
		AccessToken accessToken=new AccessToken();
		accessToken.initAccessToken();
		
//		Login login=new Login();
//		for(Map.Entry<String,AccessInfo> access:AccessToken.accessMap.entrySet()){
//			
//			WeiboResponse loginresp=login.loginWeibo(access.getValue().getName(), access.getValue().getPassword());
//			access.getValue().setSession(loginresp.getSession());
////			System.out.println(loginresp.getSession());
//		}
		
		
		
		
		
		
		 
		 List<File> filelist=this.getAllRule();
		 
		 RuleService rule=new RuleService();
		 
		 if(filelist!=null && filelist.size()>0){
			for(File file:filelist){
				String rulestr=null;
				try {
					rulestr = IOUtil.readFileToString(file,  "utf-8");
				} catch (IOException e) {
					e.printStackTrace();
				}
				GatherBean gatherbean=rule.calculateRule(rulestr);
				if(gatherbean!=null){
					gatherbean.setId(file.getName());
					BaseRule.gatherRuleMap.put(file.getName(), gatherbean);
					System.out.println(gatherbean.getTitle());
					Task task=new Task();
					task.setGatherbean(gatherbean);
					
					Thread thread=new Thread(task);
					thread.start();
				}
			}
		 }
		 //启动7天清缓存
		 Thread thread=new Thread(new CleanLog());
		 thread.start();
		 
	}
	private List<File> getAllRule(){
		
		  List<File> filelist=new ArrayList<File>();
		  try {
			BatchRenamefile.readfile(root,filelist);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		return filelist;
	}

}
